#include "IRcom.h"

uint8_t encodeByte( uint8_t inByte )
{
	inByte = (0x40 & (inByte << 3)) | (0x10 & (inByte << 2)) | (0x04 & (inByte << 1)) | (0x01 & inByte);
	return (inByte & 0x55) | ((~((inByte & 0x55) << 1)) & 0xaa);
}

uint8_t decodeByte( uint8_t inByte )
{
	return ((inByte & 0x40) >> 3) | ((inByte & 0x10) >> 2) | ((inByte & 0x04) >> 1) | (inByte & 0x01);
}


void ir_com_init()
{
    // PE1 (Carrier wave) and PC3 (TX) as output
    PORTE.DIRSET   |= PIN1_bm;
	USARTPORT.DIRSET |= PIN3_bm;
	USARTPORT.PIN3CTRL |= PORT_INVEN_bm;
    // PC2 (RX) as input
    USARTPORT.DIRCLR   = PIN2_bm; 

<<<<<<< HEAD
<<<<<<< HEAD
	// Carrier wave generation
=======
/*	// Carrier wave generation
>>>>>>> origin/master
=======
/*	// Carrier wave generation
>>>>>>> origin/master
    TCE0.CTRLB = TC_WGMODE_SS_gc; // Single Slope PWM as Waveform Generation mode. 
    TC0_ConfigClockSource(&TCE0, TC_CLKSEL_DIV1_gc);
    TC_SetPeriod(&TCE0, 421);     // 32MHz / 2 / 421 = 38KHz
    TC_SetCompareB(&TCE0, 210);
    TCE0.CTRLB |= TC0_CCBEN_bm;   // Enable the CC channel

    // Use USARTC1 and initialize buffers
    USART_InterruptDriver_Initialize(&USART_data, &USART, USART_DREINTLVL_LO_gc);
    // USARTC1, 8 Data bits, No Parity, 1 Stop bit
    USART_Format_Set(USART_data.usart, USART_CHSIZE_8BIT_gc,
                     USART_PMODE_DISABLED_gc, false);
    // Enable RXC and TXC interrupts
	USART_RxdInterruptLevel_Set(USART_data.usart, USART_RXCINTLVL_LO_gc);
	USART.CTRLA |= USART_TXCINTLVL_LO_gc;
	USART_Baudrate_Set(&USART, 3329, -3);  // 2400 Baud

	/* Enable both RX and TX. */
	USART_Rx_Enable(USART_data.usart);
	USART_Tx_Enable(USART_data.usart);

	// Enable PMIC interrupt level low
	PMIC.CTRL |= PMIC_LOLVLEX_bm;
<<<<<<< HEAD
<<<<<<< HEAD

=======
*/
>>>>>>> origin/master
=======
*/
>>>>>>> origin/master
	// Enable global interrupts
	sei();
}

//  Receive complete interrupt service routine.
ISR( USARTC1_RXC_vect )
{
    USART_RXComplete( &USART_data );
}

//  Transmit complete interrupt servies routine
ISR( USARTC1_TXC_vect )
{
//	LEDPORT.OUTSET = 0xf0;
}


//  Data register empty  interrupt service routine.
ISR( USARTC1_DRE_vect )
{
    USART_DataRegEmpty( &USART_data );
}


